<template>
  <div>
    <button type="button" @click="addUser">添加</button>
    <button type="button" @click="saveUser">保存</button>
    <label for="id">编号</label>
    <input id="id" type="text" v-model="user.id" />
    <label for="name">姓名</label>
    <input id="name" type="text" v-model="user.name" />

    <label for="age">年龄</label>
    <input id="age" type="text" v-model="user.age" />

    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>Name</th>
          <th>Age</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(user, index) in users" :key="user.id">
          <td>{{ user.id }}</td>
          <td>{{ user.name }}</td>
          <td>{{ user.age }}</td>
          <td>
            <button type="button" @click="delByIndex(index)">DEL</button>
            <button type="button" @click="editByIndex(index)">Edit</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { ref } from 'vue'
let current_index = -99
const users = ref([
  {
    id: 1,
    name: 'John',
    age: 30
  },
  {
    id: 2,
    name: 'John',
    age: 30
  },
  {
    id: 3,
    name: 'John',
    age: 30
  },
  {
    id: 4,
    name: 'John',
    age: 30
  }
])

const user = ref({ id: 4, name: 'John', age: 30 })

const addUser = () => {
  current_index = -1
  // users.value.push({
  //   id: 5,
  //   name: 'John',
  //   age: 30
  // })
  user.value = {
    id: 0,
    name: 'John',
    age: 30
  }
}

const delByIndex = (index) => {
  users.value.splice(index, 1)
  console.log(index)
}

const editByIndex = (index) => {
  current_index = index
  //  以下是错误的，我们需要一个克隆对象
  user.value = JSON.parse(JSON.stringify(users.value[index]))
  console.log(user.value)
}

const saveUser = () => {
  if (current_index == -1) {
    users.value.push(user.value)
    current_index = -99
    user.value = {
      id: 0,
      name: 'John',
      age: 30
    }
  } else {
    users.value.splice(current_index, 1, user.value)
  }
}
</script>

<style lang="scss" scoped></style>
